package org.lemon.transport.coap.client;

import org.eclipse.californium.core.CoapClient;
import org.eclipse.californium.core.CoapResponse;
import org.eclipse.californium.core.Utils;
import org.eclipse.californium.elements.DtlsEndpointContext;
import org.eclipse.californium.elements.EndpointContext;
import org.eclipse.californium.elements.exception.ConnectorException;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.Principal;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class NoSecGetOtaPackageClient {

    public static void main(String[] args) throws URISyntaxException {

        String host = "127.0.0.1";
        int port = 5683;
        String accessToken = "accessToken";

        String url = "coap://" + host + ":" + port + "/ws/" + accessToken + "?title=&version=&size=&chunk=";

        CoapClient coapClient = new CoapClient(url);
        test(coapClient);
    }

    public static void test(CoapClient coapClient) {

        CoapResponse response = null;
        try {
            response = coapClient.get();
        } catch (ConnectorException | IOException e) {
            System.err.println("Error occurred while sending request: " + e);
            System.exit(-1);
        }
        if (response != null) {

            System.out.println(response.getCode() + " - " + response.getCode().name());
            System.out.println(response.getOptions());
            System.out.println(response.getResponseText());
            System.out.println();
            System.out.println("ADVANCED:");
            EndpointContext context = response.advanced().getSourceContext();
            Principal identity = context.getPeerIdentity();
            if (identity != null) {
                System.out.println(context.getPeerIdentity());
            } else {
                System.out.println("anonymous");
            }
            System.out.println(context.get(DtlsEndpointContext.KEY_CIPHER));
            System.out.println(Utils.prettyPrint(response));
        } else {
            System.out.println("No response received.");
        }
    }
}
